<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\MaintainerRequest;
use App\Models\V1\AdminUser;
use App\Models\V1\BasicMaintainers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Log;

class MaintainersController extends Controller
{
    /**
     * 显示维修人员数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.maintainers');
    }

    /**
     * 获取维修人员数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的维修人员数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的维修人员数据
        $data = $this->getMaintainersList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['mobile'] = $item['mobile'];
                    $formatItem['telephone'] = $item['telephone'];
                    $formatItem['avatar'] = $item['avatar'];
                    $formatItem['email'] = $item['email'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条维修人员数据显示界面（适用于新增addData、查看viewData、编辑editData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')){
            case 'addData':
                $data['randomCode'] = 'MTR' . uniqid();
                return view('v1.form.maintainer_item', $data);
                break;
            case 'editData':
                $data['code'] = $request->input('code');
                $maintainer = $this->getMaintainerByCode($data['code']);
                $data['itemData'] = $maintainer;
                return view('v1.form.maintainer_item', $data);
                break;
            case 'viewData':
                $data['code'] = $request->input('code');
                $maintainer = $this->getMaintainerByCode($data['code']);
                $data['itemData'] = $maintainer;
                return view('v1.form.maintainer_item', $data);
                break;

        }
    }

//    /**
//     * 显示教职工数据导入页面
//     *
//     * @param Request $request
//     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
//     */
//    public function importView(Request $request)
//    {
//        // 获取登录用户
//        $loginUser = Auth::user();
//
//        $data['view'] = $request->input('view');
//        $data['code'] = $loginUser->getAttribute('code');
//
//        return view('v1.form.upload_excel', $data);
//    }

    /**
     * 更新维修人员基本信息(单元格)
     *
     * @param MaintainerRequest $request
     * @return array
     */
    public function updateCellData(MaintainerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '维修员代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateMaintainer($request);

            // 更新维修员信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '维修员代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新维修员基本信息
     *
     * @param MaintainerRequest $request
     * @return array
     */
    public function updateData(MaintainerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '维修员代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateMaintainer($request);

            // 更新维修员信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '维修员代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '维护人员[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
//            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '维护人员代码不能为空';
            $messages['name.required'] = '维护人员姓名不能为空';
//            $messages['captcha.required'] = '验证码不能为空';
//            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '维护人员[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除维修员基本信息
     *
     * @param MaintainerRequest $request
     * @return array
     */
    public function deleteData(MaintainerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '维修员代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateMaintainer($request);
            $code = $request->input('code');
            if ($code === 'admin') {
                $response['rspMsg']= '不可以删除管理员';
                return $response;
            }

            // 删除维修员信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '维修员代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除维修员基本信息
     *
     * @param MaintainerRequest $request
     * @return array
     */
    public function deleteBatchData(MaintainerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '维修员批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除维修员信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '维修员批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的维修员列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getMaintainersList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = BasicMaintainers::orderBy('created_at', 'asc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = BasicMaintainers::where('name', 'like', '%' . $keywords . '%')->orderBy('created_at', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 根据维修员代码获取对应教职工信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getMaintainerByCode($code)
    {
        $maintainer = BasicMaintainers::where('code', $code)->first();
        return $maintainer;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新维修员信息验证请求
     *
     * @param Request $request
     */
    private function validateMaintainer(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新维修员信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
            ];
            if ($request->input('mobile') !== "") {
                $updateData['mobile'] = $request->input('mobile');
            }
            if ($request->input('email') !== "") {
                $updateData['email'] = $request->input('email');
            }
            if ($request->input('telephone') !== "") {
                $updateData['telephone'] = $request->input('telephone');
            }
            if ($request->input('avatar') !== "") {
                $updateData['avatar'] = $request->input('avatar');
            }
        }

        $rspObj = BasicMaintainers::where('code', $where)
            ->update($updateData);

        return $rspObj;
    }

    /**
     * 处理更新维修员信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');

            foreach ($codeList as $code) {
                $rspObj = BasicMaintainers::where('code', $code)
                    ->where(function ($query){
                        $query->where('code','<>','admin');
                    })->delete();
                //删除登录表中的数据
                if ($rspObj){
                    //删除登录表中的数据
                    $userObj = AdminUser::where('code', $code)
                        ->where(function ($query){
                            $query->where('code','<>','admin');
                        })->first();
                    // 解除角色绑定
                    $userObj->detachRoles();
                    // 删除
                    $rspObj = $userObj->delete();
                }
            }
        } else { // 单条删除
            $rspObj = BasicMaintainers::where('code', $where)
                ->where(function ($query){
                    $query->where('code','<>','admin');
                })->delete();
            if ($rspObj){
                //删除登录表中的数据
                $userObj = AdminUser::where('code', $where)
                    ->where(function ($query){
                        $query->where('code','<>','admin');
                    })->first();
                // 解除角色绑定
                $userObj->detachRoles();
                // 删除
                $rspObj = $userObj->delete();
            }
        }

        return $rspObj;
    }

    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
            'mobile' => isset($request['mobile']) ? $request->input('mobile') : NULL,
            'telephone' => isset($request['telephone']) ? $request->input('telephone') : NULL,
            'avatar' => isset($request['avatar']) ? $request->input('avatar') : NULL,
            'email' => isset($request['email']) ? $request->input('email') : NULL,
        ];

        DB::beginTransaction(); // 开启事务
        $rspObj = BasicMaintainers::create($insertData);
        if ($rspObj){ // 维护人员添加成功，再写入用户表
            // 将维护人员写入用户表
            $insertTag = $this->registerUser($request->input('code'),true);
            if ($insertTag){
                DB::commit();
                return $insertTag;
            }else{
                DB::rollback();
                return false;
            }

        }else{ // 维护人员添加失败，数据回滚
            DB::rollback();
            return $rspObj;
        }
    }

    //向登录的数据库表中添加数据
    private function registerUser($code,$is_admin){
        $insert_data = [
            'code' => $code,
            'password' => bcrypt('123456'),
            'is_admin' => $is_admin,
        ];
        $rspObj = AdminUser::updateOrCreate(['code' => $code], $insert_data);
//        $user = AdminUser::where('code',$code)->first();
//        $role = Role::where('name','admin')->first();
//        if (!$user->hasRole('admin')) {
//            $user -> attachRole($role);
//        }
        return $rspObj;
    }
}
